package com.huang.annotation_reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class reflection08 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        //获得Class对象
        Class c1 = Class.forName("com.huang.annotation_reflection.User");

        //构造一个对象(无参构造)
        Constructor declaredConstructor = c1.getDeclaredConstructor();
        User user = (User) declaredConstructor.newInstance();

        user= (User) c1.getDeclaredConstructor().newInstance();
        System.out.println(user);

        //通过构造器创建对象
        Constructor declaredConstructor1 = c1.getDeclaredConstructor(String.class, int.class, int.class);
        User user2 = (User) declaredConstructor1.newInstance("有参构造", 20, 21);
        System.out.println(user2);

        //通过反射调用普通方法
         User user3 = (User) c1.newInstance();
        Method setName = c1.getDeclaredMethod("setName", String.class);
        //invoke()激活这个方法,第一个参数为调用的实例，第二个为想调用方法传入的参数
        setName.invoke(user3,"反射调用方法");
        System.out.println(user3.getName());

        //通过反射操作属性（不可直接操作私有属性）
        User user4 = (User) c1.newInstance();
        Field name = c1.getDeclaredField("name");
        //由于权限不够（name属性为private）,需要设置安全检测改为可以访问
        //关闭权限检查可以提高程序性能
        name.setAccessible(true);
        name.set(user4,"反射操作属性");
        System.out.println(user4.getName());

    }

}
